package com.young.coderule.common.lock;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @DESCRIPTION: 本地锁
 * @USER: Young
 * @DATE: 2022/7/29 14:41
 */
public class LocalLock implements MyLock {

    private volatile Map<String, Thread> locks = new ConcurrentHashMap<>();

    @Override
    public synchronized boolean lock(String key) {
        if(locks.containsKey(key) && locks.get(key)!=Thread.currentThread()){
            return false;
        }
        locks.put(key, Thread.currentThread());
        return true;
    }

    @Override
    public synchronized void unlock(String key) {
        if(isOwner(key)){
            locks.remove(key);
        }
    }

    @Override
    public synchronized boolean isOwner(String key) {
        return locks.containsKey(key) && locks.get(key)==Thread.currentThread();
    }

}
